import React, { useState } from 'react';
import { useParams } from 'react-router-dom';

import MeetingRoom from './MeetingRoom';
import ErrorBoundary from './ErrorBoundary';
import './MeetingRoomWrapper.css';

// 添加JSX命名空间声明
declare global {
  namespace JSX {
    interface IntrinsicElements {
      div: React.DetailedHTMLProps<
        React.HTMLAttributes<HTMLDivElement>,
        HTMLDivElement
      >;
      h1: React.DetailedHTMLProps<
        React.HTMLAttributes<HTMLHeadingElement>,
        HTMLHeadingElement
      >;
      h3: React.DetailedHTMLProps<
        React.HTMLAttributes<HTMLHeadingElement>,
        HTMLHeadingElement
      >;
      form: React.DetailedHTMLProps<
        React.FormHTMLAttributes<HTMLFormElement>,
        HTMLFormElement
      >;
      input: React.DetailedHTMLProps<
        React.InputHTMLAttributes<HTMLInputElement>,
        HTMLInputElement
      >;
      button: React.DetailedHTMLProps<
        React.ButtonHTMLAttributes<HTMLButtonElement>,
        HTMLButtonElement
      >;
      p: React.DetailedHTMLProps<
        React.HTMLAttributes<HTMLParagraphElement>,
        HTMLParagraphElement
      >;
      span: React.DetailedHTMLProps<
        React.HTMLAttributes<HTMLSpanElement>,
        HTMLSpanElement
      >;
      ol: React.DetailedHTMLProps<
        React.OlHTMLAttributes<HTMLOListElement>,
        HTMLOListElement
      >;
      li: React.DetailedHTMLProps<
        React.LiHTMLAttributes<HTMLLIElement>,
        HTMLLIElement
      >;
    }
  }
}

// 自定义错误回退UI
const MeetingErrorFallback: React.FC<{ error?: Error | null }> = ({
  error,
}) => (
  <div className="meeting-error-fallback">
    <h2>会议加载失败</h2>
    <p>抱歉，加载会议室时出现了问题。</p>
    {error && <p className="error-message">错误信息: {error.message}</p>}
    <div className="error-actions">
      <button onClick={() => window.location.reload()}>刷新页面</button>
      <button onClick={() => (window.location.href = '/')}>返回首页</button>
    </div>
  </div>
);

const MeetingRoomWrapper: React.FC = () => {
  const { roomId } = useParams<{ roomId: string }>();
  const [userId] = useState<string>(
    `user_${Math.floor(Math.random() * 10000)}`
  );
  const [joined, setJoined] = useState<boolean>(!!roomId);
  const [meetingRoomId, setMeetingRoomId] = useState<string>(roomId || '');
  const [localIP] = useState<string>(window.location.hostname || 'localhost');
  const [showHelp, setShowHelp] = useState<boolean>(false);

  const joinMeeting = (e: React.FormEvent<HTMLFormElement>): void => {
    e.preventDefault();
    if (meetingRoomId.trim()) {
      setJoined(true);
    }
  };

  if (joined) {
    return (
      <ErrorBoundary fallback={<MeetingErrorFallback />}>
        <div style={{ backgroundColor: '#ffffff' }}>
          <MeetingRoom
            roomId={meetingRoomId}
            userId={userId}
            userName={`用户 ${userId.split('_')[1]}`}
            localIP={localIP}
          />
        </div>
      </ErrorBoundary>
    );
  }

  return (
    <div className="join-screen">
      <h1>视频会议</h1>
      <form onSubmit={joinMeeting}>
        <input
          type="text"
          placeholder="输入会议号"
          value={meetingRoomId}
          onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
            setMeetingRoomId(e.target.value)
          }
          required
        />
        <button type="submit">加入会议</button>
      </form>

      <div className="connection-info">
        <p>
          你的用户ID: <span className="highlight">{userId}</span>
        </p>
        <p>
          本机地址: <span className="highlight">http://{localIP}:3000</span>
        </p>
        <p className="help-text" onClick={() => setShowHelp(!showHelp)}>
          {showHelp ? '隐藏帮助' : '如何加入会议?'}
        </p>

        {showHelp && (
          <div className="help-box">
            <h3>同一WiFi下的其他设备加入方法:</h3>
            <ol>
              <li>确保所有设备连接到同一个无线网络</li>
              <li>在其他设备浏览器中输入上面的本机地址</li>
              <li>输入相同的会议号加入</li>
              <li>允许浏览器使用摄像头和麦克风</li>
            </ol>
            <p className="note">
              注意: 如果无法连接，请检查防火墙设置或尝试关闭杀毒软件
            </p>
          </div>
        )}
      </div>
    </div>
  );
};

export default MeetingRoomWrapper;
